var union = require('union');

var fs = require('fs');
var request = require('request');
var mkdirp = require('mkdirp');
var url = require('url');
var colors = require('colors');
var httpProxy = require('http-proxy');

var ecstatic = require('./ecstatic/ecstatic');
var mime = require('./mime/mime');
var router = require('./router');
var config = require("./config");
var cacheManifest = require('./manifestRequest');

var relativePath = config.relativePath;
var x5UIPath = config.serverPath;
var proxy = httpProxy.createProxyServer({target:x5UIPath});

var server = union.createServer({
    before: [
        function (req, res) {
            console.log("\n---------------------------------------------------------------------------------------");
            console.log('\n收到请求:' + req.url);
            res.emit('next');
        },
        function(req,res){
            if(isStaticRequest(req)){
                // 处理静态资源
                return parseStaticFile(req,res);
            }else if(router.getRouter(req.url)){
                return parseStaticFile(req,res);
            }else{
                console.log(("应该js 中拦截掉得请求：当前请求为非静态资源，直接转掉"+req.url).blue);
                proxy.web(req, res, { target: x5UIPath});
            }
        },
        function(req,res){
          console.log("\necstatic 静态服务器开始处理请求：" + req.url);
          res.emit('next');
        },
        ecstatic({
            root: "../public/",
            cache: -1,
            showDir : true,
            autoIndex: false
        })
    ]
});

var port = config.localPort;
server.listen(port);
console.log("\necstatic 静态服务器开始服务 监听端口 ：" + port);
cacheManifest(function(error){
    if(error){
        console.log("\n通过manifest缓存文件失败：" + error);
    }else{
        console.log("\n 离线资源准备完毕！");
        if(config.autoExit){
            process.exit();
        }
    }
});


var isStaticRequest = function(req){
    if(req.method != 'GET'){
        return false;
    }
    var contentType = mime.lookup(req.url);
    if(contentType && "application/octet-stream"!=contentType){
        console.log('根据contentType：'+ contentType +"判定为静态资源");
        return true;
    }else{
        return false;
    }
};

var parseStaticFile = function(req,res){
    var getLocalPath = function(){
        var routerPath = router.getRouter(req.url);
        return routerPath ? relativePath + routerPath :relativePath + req.url;
    };
    var localPath = getLocalPath();
    var remotePath = x5UIPath + req.url;
    console.log('\n对应本地文件：'+ localPath +"服务器端文件:" + remotePath);
    fs.lstat(localPath,function(err, stats){
        if(err){
            console.log('\n本地文件不存在：'+localPath);
            request.head(remotePath, function(err, response, body){
                console.log("\n请求服务器端文件进行缓存:" + remotePath);
                var localPathUrl = url.parse(localPath);
                var urlPath = localPathUrl.path;
                var urlArray = urlPath.split('/');
                var urlFileName = urlArray.splice(urlArray.length-1);
                var urlDirPath = urlArray.join('/');
                console.log("\n准备创建目录:" + urlDirPath);
                mkdirp(urlDirPath, function(err){
                    if(err){
                        console.error("创建本地目录失败：" +err);
                    }else{
                        console.log("\n收到服务器端"+remotePath+"文件并进行缓存到本地:" + localPath);
                        var writeStream = fs.createWriteStream(localPath);
                        var contentType = mime.lookup(remotePath);
                        var options = {
                            url: remotePath,
                            headers: {
                                'User-Agent': 'x-slm',
                                'content-type':contentType
                            }
                        };
                        request(options).pipe(writeStream);
                        writeStream.on('close',function(){
                            console.log("\n本地缓存完毕：("+ localPath + ")继续进行静态服务器处理");
                            res.emit('next');
                        });
                    }

                });
            });
        }else{
            console.log('\n本地文件已经存在：（'+localPath +") 继续进行静态服务器处理");
            res.emit('next');
        }
    });
}
